package core

import (
	"bytes"
	"math/rand"
	"time"

	"golang.org/x/crypto/bcrypt"
)

// EncryptPassword 密码加密
func EncryptPassword(pwd string) (string, error) {
	hash, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
	return string(hash), err
}

// VerifyPassword 验证密码一致性
func VerifyPassword(enPwd, pwd string) error {
	return bcrypt.CompareHashAndPassword([]byte(enPwd), []byte(pwd))
}

// RandString 生成制定长度的随机字符串
func RandString(size int) string {
	letters := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"
	length := len(letters)
	rand.NewSource(time.Now().UnixNano()) // 产生随机种子
	var s bytes.Buffer
	for i := 0; i < size; i++ {
		s.WriteByte(letters[rand.Int63()%int64(length)])
	}
	return s.String()
}
